package cn.jiaqiang.chatgpt.data.domain.weixin.service.message;


import cn.jiaqiang.chatgpt.data.domain.weixin.model.entity.UserBehaviorMessageEntity;
import cn.jiaqiang.chatgpt.data.domain.weixin.model.valobj.MsgTypeVO;
import cn.jiaqiang.chatgpt.data.domain.weixin.service.IBehaviorMessageService;
import cn.jiaqiang.chatgpt.data.domain.weixin.service.IWeiXinBehaviorService;
import cn.jiaqiang.chatgpt.data.types.enums.BehaviorMessageChannel;
import cn.jiaqiang.chatgpt.data.types.exception.ChatGPTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashMap;
import java.util.Map;


/**
 * @description 受理用户行为接口实现类
 */
@Service
public class WeiXinBehaviorService implements IWeiXinBehaviorService {

    private static final Logger log = LoggerFactory.getLogger(WeiXinBehaviorService.class);
    private final Map<BehaviorMessageChannel, IBehaviorMessageService> messageServiceMap = new HashMap<>();
    public WeiXinBehaviorService(BehaviorMessage401Service message401Service, BehaviorMessageDefaultService defaultService) {
        messageServiceMap.put(BehaviorMessageChannel.OPEN_NEW_USER_ACCOUNT, message401Service);
        messageServiceMap.put(BehaviorMessageChannel.DEFAULT, defaultService);
    }

    /**
     * 1. 用户的请求行文，分为事件event、消息text，这里我们只处理消息内容
     * 2. 用户行为、消息类型，是多样性的，这部分如果用户有更多的扩展需求，可以使用设计模式【模板模式 + 策略模式 + 工厂模式】，分拆逻辑。
     */
    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 350, propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    public String acceptUserBehavior(UserBehaviorMessageEntity userBehaviorMessageEntity) {
        // Event 事件类型，忽略处理
        if (MsgTypeVO.EVENT.getCode().equals(userBehaviorMessageEntity.getMsgType())) {
            return "";
        }

        // Text 文本类型
        if (MsgTypeVO.TEXT.getCode().equals(userBehaviorMessageEntity.getMsgType())) {
            // 拿到 service
            IBehaviorMessageService behaviorMessageService =
                    messageServiceMap.getOrDefault(BehaviorMessageChannel
                                    .getContent(userBehaviorMessageEntity.getContent()),
                    // map 默认值
                    messageServiceMap.get(BehaviorMessageChannel.DEFAULT));
            // 处理用户消息
            log.info("开始处理用户消息(微信公众号消息...)");
            return behaviorMessageService.doBehaviorMessage(userBehaviorMessageEntity);
        }
        throw new ChatGPTException(userBehaviorMessageEntity.getMsgType() + " 未被处理的行为类型 Err！");
    }


}
